package com.aiyige.page.my.merchandisemanagement;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.eventbus.EventMMPublishProgressStatusUpdate;
import com.aiyige.base.eventbus.EventMMUploadUpdate;
import com.aiyige.page.my.merchandisemanagement.adapter.MMPagerAdapter;
import com.aiyige.page.my.merchandisemanagement.model.TabItem;
import com.aiyige.page.publish.publishresult.PublishResult;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.flyco.tablayout.SlidingTabLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Track("商品管理页")
@Route(path = ARouterConfig.MerchandiseManagementPage, extras = ARouterConfig.EXTRA_NEED_LOGIN)
public class MerchandiseManagementPage extends BaseActivity {
    public static final String TAG = MerchandiseManagementPage.class.getSimpleName();
    public static final int HANDLE_SEARCH = 1;
    public static final int REQUEST_CODE_PUBLISH = 1;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.titleActionBtn)
    ImageView titleActionBtn;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.mainVp)
    ViewPager mainVp;
    List<TabItem> tabItemList;
    MMPagerAdapter mmPagerAdapter;
    CommonBottomDialogFragment mmFilterDialog;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;
    BroadcastReceiver broadcastReceiver;
    @Autowired
    int targetTab = TabItem.TAB_ID_LEARN_VIDEO;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_merchandise_management);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        mmFilterDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.mm_filter_dialog)
                .viewIdList(R.id.allBtn, R.id.publishedBtn, R.id.notPublishedBtn, R.id.rejectBtn, R.id.inReviewBtn)
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        Integer filter = null;
                        switch (view.getId()) {
                            case R.id.allBtn:
                                filter = null;
                                break;
                            case R.id.publishBtn:
                                filter = PublishUtil.PROGRESS_STATUS_PUBLISHED;
                                break;
                            case R.id.notPublishedBtn:
                                filter = PublishUtil.PROGRESS_STATUS_NOT_PUBLISHED;
                                break;
                            case R.id.inReviewBtn:
                                filter = PublishUtil.PROGRESS_STATUS_IN_REVIEW;
                                break;
                            case R.id.rejectBtn:
                                filter = PublishUtil.PROGRESS_STATUS_REJECT;
                                break;
                        }
                        mmPagerAdapter.notifyFilterChanged(filter);
                    }
                })
                .build();
        tabItemList = new LinkedList<>();
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchStr = inputEt.getText().toString();
                    if (!TextUtils.isEmpty(searchStr.trim())) {
                        ARouter.getInstance()
                                .build(ARouterConfig.MMSearchGroupPage)
                                .withString("keyword", searchStr.trim())
                                .navigation();
                    }
                    return true;
                }
                return false;
            }
        });
        inputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputEtClearBtn.setVisibility(s.length() == 0 ? View.INVISIBLE : View.VISIBLE);
            }
        });
        initView();
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case PublishUtil.ACTION_UPLOAD_UPDATE:
                            EventBus.getDefault().post(new EventMMUploadUpdate());
                            break;
                        case PublishUtil.ACTION_PUBLISH_PROGRESS_STATUS_UPDATE:
                            EventBus.getDefault().post(new EventMMPublishProgressStatusUpdate());
                            break;
                    }
                } catch (Exception e) {

                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PublishUtil.ACTION_UPLOAD_UPDATE);
        intentFilter.addAction(PublishUtil.ACTION_PUBLISH_PROGRESS_STATUS_UPDATE);
        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(broadcastReceiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    public void initView() {
        tabItemList.add(TabItem.newBuilder()
                .tabId(TabItem.TAB_ID_LEARN_VIDEO).tabName(StringUtils.getString(R.string.learn_video))
                .build());
        tabItemList.add(TabItem.newBuilder()
                .tabId(TabItem.TAB_ID_MAJOR_COURSE)
                .tabName(StringUtils.getString(R.string.major_course))
                .build());
//        tabItemList.add(TabItem.newBuilder()
//                .tabId(TabItem.TAB_ID_TRAING_CLASS)
//                .tabName(StringUtils.getString(R.string.traing_class))
//                .build());
//        tabItemList.add(TabItem.newBuilder()
//                .tabId(TabItem.TAB_ID_TRAING_CARD)
//                .tabName(StringUtils.getString(R.string.traing_card))
//                .build());
        mmPagerAdapter = new MMPagerAdapter(getSupportFragmentManager(), tabItemList);
        mainVp.setAdapter(mmPagerAdapter);
        tabLayout.setViewPager(mainVp);
        jumpToTargetTab();
    }

    public void jumpToTargetTab() {
        int tabItemListSize = tabItemList.size();
        for (int i = 0; i < tabItemListSize; ++i) {
            if (tabItemList.get(i).getTabId() == targetTab) {
                mainVp.setCurrentItem(i, false);
                return;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PUBLISH:
                PublishResult publishResult = PublishResult.obtainPublishResult(data);
                if (publishResult != null) {
                    publishResult.setTargetTab(PublishResult.TARGET_TAB_INVALID);
                }
                PublishResult.handlePublishResult(this, publishResult);
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }

    }

    @OnClick({R.id.titleBackBtn, R.id.titleActionBtn, R.id.inputEtClearBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.titleActionBtn:
                mmFilterDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.cancelBtn:
                break;
        }
    }
}
